// src/store/modules/userInfo.js
import { defineStore } from "pinia";
import Local from "tools-utils/storage";
import router from "@/router";

import { setAuthToken, ensureConnected, disconnect } from "@/core/registerMessageHandlers";

export const useUserInfoStore = defineStore("userInfoStore", {
  state: () => ({
    token: "",
    userInfo: {},
    roles: [],
    auths: [],
    loginCandidates: [],
  }),

  getters: {
    hasAuth: state => authKeys => Array.isArray(authKeys) && state.auths.some(key => authKeys.includes(key)),
    hasAuthAll: state => authKeys => Array.isArray(authKeys) && authKeys.every(key => state.auths.includes(key)),
  },

  actions: {
    /** 内部：消费登录第二步结果（保存并连上 SSE） */
    _consumeChooseResp(data = {}) {
      const token = data.token || "";
      this.token = token;
      this.userInfo = data;
      this.roles = Array.isArray(data.roles) ? data.roles : [];

      Local.set("token", token);
      Local.set("userInfo", this.userInfo);
      Local.set("roles", this.roles);

      try {
        setAuthToken(token); // URL 鉴权会拼到 ?access_token=xxx；Cookie 鉴权保留也无妨
        ensureConnected(); // 启动/刷新 SSE 连接
      } catch (e) {
        console.warn("[MsgCenter] connect on login failed:", e);
      }
    },

    /** 第一步：密码登录 -> 候选客户列表（不落 token） */
    async LoginByPwd(payload = {}) {
      const res = await Api.login.LoginByPwd({
        mobile: payload.mobile,
        pass: payload.password,
        code: payload.imgCode,
        cid: payload.captchaId,
      });
      const list = res?.data ?? [];
      this.loginCandidates = Array.isArray(list) ? list : [];
      return this.loginCandidates;
    },

    /** 第一步：短信登录 -> 候选客户列表（不落 token） */
    async LoginByCode(payload = {}) {
      const res = await Api.login.LoginByCode({
        mobile: payload.mobile,
        code: payload.smsCode,
      });
      const list = res?.data ?? [];
      this.loginCandidates = Array.isArray(list) ? list : [];
      return this.loginCandidates;
    },

    /** 第二步：选择客户 -> 返回 token 和完整用户信息（此时落 token 并连接） */
    async ChooseUser({ id, sign, tenantId }) {
      const res = await Api.login.LoginChooseUser({ id, sign, tenantId });
      const data = res?.data ?? {};
      this._consumeChooseResp(data);
      return data;
    },

    /** 应用启动恢复：若本地已有 token，恢复用户信息并连上 SSE */
    RestoreSessionAndWS() {
      const token = Local.get("token") || "";
      if (token) {
        this.token = token;
        this.userInfo = Local.get("userInfo") || {};
        this.roles = Local.get("roles") || [];
        try {
          setAuthToken(token);
          ensureConnected();
        } catch (e) {
          console.warn("[MsgCenter] ensureConnected on boot failed:", e);
        }
      }
    },

    /** 获取权限点 */
    GetUserAuths() {
      return new Promise((resolve, reject) => {
        Api.user
          .GetUserAuths()
          .then(res => {
            const data = res?.data ?? [];
            this.auths = Array.isArray(data) ? data : [];
            Local.set("user-auths", this.auths);
            resolve(res);
          })
          .catch(reject);
      });
    },

    /** 退出登录：清缓存并断开 SSE */
    Logout() {
      try {
        disconnect(); // 主动断开 SSE，停止重连
      } catch (e) {
        console.warn("[MsgCenter] disconnect on logout error:", e);
      }

      if (typeof this.$reset === "function") {
        this.$reset();
      } else {
        this.token = "";
        this.userInfo = {};
        this.roles = [];
        this.auths = [];
        this.loginCandidates = [];
      }

      try {
        Local.clear();
      } catch (e) {
        console.warn("[Logout] Local.clear error:", e);
      }

      router.replace("/login");
    },
  },

  persist: true,
});
